<template> 
  <a-row class="header-box">
    <a-page-header
      :title="$route.meta.title"
    >
    </a-page-header>
  </a-row>
  <a-divider :style="{marginTop:0}" />
  <a-alert
      message="说明："
      type="info"
      show-icon
    > 
    <template v-slot:icon><smile-outlined /></template>
    <template #description>
      <div>将种子按站点、分类进行归类管理；</div>
      <div>推送至下载器按指定目录进行下载，格式为：[基础下载目录]/[站点目录]/[分类目录]/。</div>
      <div>例如：/Downloads/BTSCHOOL/Movies/xxxxxx.mp4</div>
    </template>
  </a-alert>
  <a-divider :style="{marginBottom: 0}"/>
  <a-row class="search-box">
    <a-form layout="horizontal" :label-col="{span:2}" :wrapper-col="{span:22}" labelAlign="left">
      <a-form-item label="分类">
        <a-checkbox-group v-model:value="searchForm.category">
          <a-checkbox v-for="option in categoryOptions" :key="option.id" :value="option.id" name="category">
            {{ option.name }}
          </a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="站点">
        <a-checkbox-group v-model:value="searchForm.site">
          <a-checkbox v-for="option in siteOptions" :key="option.id" :value="option.id" name="site">
            {{ option.name }}
          </a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="下载器">
        <a-checkbox-group v-model:value="searchForm.client">
          <a-checkbox v-for="option in clientOptions" :key="option.id" :value="option.id" name="client">
            {{ option.name }}
          </a-checkbox>
        </a-checkbox-group>
      </a-form-item>
    </a-form>
    <a-col :span="24" align="center">
      <a-button
        type="primary"
        size="small"
        @click="doSearch"
      >
        <template v-slot:icon><FilterFilled /></template>
        筛选
      </a-button>
    </a-col>
  </a-row>
  <!-- 操作栏 -->
  <a-row class="operation-box">
    <a-col :span="4">
      <a-input-search
        v-model:value="searchForm.keyword"
        @search="doSearch"
        placeholder=""
        enter-button
        allowClear
      />
    </a-col>
    <a-col :span="20" align='right'>
      <a-space>
        <a-dropdown-button @click="toAutoLink(false)">
          自动链接
          <template v-slot:overlay>
            <a-menu>
              <a-menu-item @click="toAutoLink(true)">测试自动链接</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown-button>
        <a-button type="default" @click="toAdd">
          <template v-slot:icon><plus-outlined/></template>
          添加
        </a-button>
        <!-- <a-dropdown :disabled="pulling">
          <a-button type="default"><template #icon><CloudDownloadOutlined /></template>从下载服务同步</a-button>
          <template v-slot:overlay>
            <a-menu @click="doPull">
              <a-menu-item v-for="op in clientOptions" :key="op.id">{{op.name}}</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown> -->
        <a-button type="default" @click="reloadData">
          <template v-slot:icon><reload-outlined/></template>
        </a-button>
      </a-space>
    </a-col>
  </a-row>
  <!-- 数据表格 -->
  <a-row class="table-list-box">
      <a-table rowKey="id" :loading="dataLoading" :columns="columns" :data-source="data" :pagination="pagination" 
        @change="tableChange"
        >
        <template #bodyCell="{ column, record}">
          <template v-if="column.key === 'name'">
            <a-tooltip v-if="record.name" >
              <template v-slot:title>
                {{ record.btname }}
              </template>
              {{ record.name }}
            </a-tooltip>
          </template>
          <template v-else-if="column.key === 'siteid'">
            <a-select
              v-model:value="record.siteid"
              size="small"
              style="width:100%"
              @change="doUpdate({id: record.id, siteid: record.siteid})"
            >
              <a-select-option v-for="option in siteOptions" :key="option.id" :value="option.id">
                {{ option.name }}
              </a-select-option>
            </a-select>
          </template>
          <template v-else-if="column.key === 'categoryid'">
            <a-select
              v-model:value="record.categoryid"
              size="small"
              style="width:100%"
              @change="doUpdate({id: record.id, categoryid: record.categoryid})"
            >
              <a-select-option v-for="option in categoryOptions" :key="option.id" :value="option.id">
                {{ option.name }}
              </a-select-option>
            </a-select>
          </template>
          <template v-else-if="column.key === 'clientid'">
            <a-select
              v-model:value="record.clientid"
              size="small"
              style="width:80%"
              @change="doUpdate({id: record.id, clientid: record.clientid})"
              :disabled="record.status != 'unlink'"
            >
              <a-select-option v-for="option in clientOptions" :key="option.id" :value="option.id">
                {{ option.name }}
              </a-select-option>
            </a-select>
            <a-button size="small" @click="toLink(record)" 
              style="width:20%">
              <template v-slot:icon><LinkOutlined /></template>
            </a-button>
          </template>
          <template v-else-if="column.key === 'status'">
            {{ record.status==='unlink'?'未推送':(record.status==='linked'?'已推送':'推送中') }}
          </template>
          <template v-else-if="column.key === 'linkDir'">
            <a-tooltip v-if="record.linkDir" >
              <template v-slot:title>
                {{ record.linkDir }}
              </template>
              <a-badge status="processing" text="" />
            </a-tooltip>
            <a-badge v-else status="default" text="" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button size="small" shape="round" @click="toView(record)">
                <template v-slot:icon><EyeFilled /></template>
              </a-button>
              <a-button size="small" shape="round" @click="toEdit(record)">
                <template v-slot:icon><EditFilled /></template>
              </a-button>
              <a-button size="small" shape="round" @click="toRemove(record)">
                  <template v-slot:icon><DeleteFilled /></template>
              </a-button>
              <!-- <a-popconfirm
                title="您确定要删除该记录吗?"
                ok-text="删除"
                cancel-text="取消"
                @confirm="doDelete(record.id)"
              > 
                <a-button size="small" shape="round">
                  <template v-slot:icon><DeleteFilled /></template>
                </a-button>
              </a-popconfirm> -->
            </a-space>
          </template>
        </template>
        
      </a-table>
  </a-row>
  <!-- 新增弹窗 -->
  <AddModal ref="addModal" :success='reloadData' :siteOptions="siteOptions" :categoryOptions="categoryOptions" :clientOptions="clientOptions" :libraryOptions="libraryOptions"/>
  <!-- 详情窗口 -->
  <DetailModal ref="detailModal" :siteOptions="siteOptions" :categoryOptions="categoryOptions" :clientOptions="clientOptions" :libraryOptions="libraryOptions"/>
  <!-- 删除确认窗口 -->
  <a-modal v-model:visible="removeShow" title="确认删除？" okText="删除" @ok="doRemove" :confirmLoading="removeLoading">
    <a-form ref="removeForm" :model="removeForm" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="从系统删除" name="remove">
        <a-switch v-model:checked="removeForm.remove" />
      </a-form-item>
      <a-divider/>
      <a-form-item label="从下载器删除" name="del">
        <a-switch v-model:checked="removeForm.del" />
      </a-form-item>
      <a-form-item label="同时删除文件" name="delFile">
        <a-switch v-model:checked="removeForm.delFile" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 关联下载器窗口 -->
  <a-modal v-model:visible="linkShow" title="关联到下载器" okText="确定" @ok="doLink" :confirmLoading="linkLoading">
    <a-form ref="linkForm" :model="linkForm" :rules="linkRules">
      <a-form-item label="下载器" name="clientid">
        <a-select
          v-model:value="linkForm.clientid"
          size="small"
          style="width:100%"
        >
          <a-select-option v-for="option in clientOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="hash值" name="hashString">
        <a-input v-model:value="linkForm.hashString" allow-clear/>
      </a-form-item>
      <a-divider/>
      <a-form-item label="在下载器检查" name="checkInClient">
        <a-switch v-model:checked="linkForm.checkInClient" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import CommonUtil from '../../utils/CommonUtil.js'
import BaseApi from '../../api/api.js'
import { SmileOutlined, SearchOutlined, ReloadOutlined, PlusOutlined, EditFilled, DeleteFilled, CloudDownloadOutlined, FilterFilled, EyeFilled, LinkOutlined  } from '@ant-design/icons-vue'
import AddModal from './Add.vue'
import DetailModal from './Detail.vue'
import TorrentApi from '../../api/TorrentApi.js'
export default {
  name: 'Torrent',
  components: {
    SmileOutlined,
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditFilled,
    DeleteFilled,
    CloudDownloadOutlined, 
    FilterFilled,
    EyeFilled,
    LinkOutlined,
    AddModal,
    DetailModal
  },
  data() {
    return {
      module: 'torrent',
      labelCol: { span: 7 },
      wrapperCol: { span: 17 },
      siteOptions: [],
      categoryOptions: [],
      clientOptions: [],
      libraryOptions: [],
      searchForm: {
        keyword: '',
        category: [],
        site: [],
        client: [],
        status: [],
        linkDir: []
      },
      pagination: {
        size: 'small', 
        defaultPageSize: 20,
        showLessItems: true,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `当前第 ${range[0]} 到第 ${range[1]} 条数据，共 ${total} 条`,
      },
      columns: [
        // {
        //   title: '序号',
        //   fixed: 'left',
        //   width: 80,
        //   customRender: ({ index })=>`${index+1}`,
        // },
        {
          title: '添加时间',
          dataIndex: 'addtime',
          key: 'addtime',
          width: 200,
          sorter: true,
          customRender: ({record})=>{return CommonUtil.formatTimestamp(record.addtime)}
        },
        { 
          title: '种子名称',
          dataIndex: 'name',
          key: 'name',
          width: 400,
        },
        // {
        //   title: '下载链接',
        //   dataIndex: 'address',
        //   key: 'address',
        //   ellipsis: true,
        // },
        {
          title: '站点',
          dataIndex: 'siteid',
          key: 'siteid',
          width: 150,
        },
        {
          title: '分类',
          dataIndex: 'categoryid',
          key: 'categoryid',
          width: 150,
        },
        {
          title: '下载器',
          dataIndex: 'clientid',
          key: 'clientid',
          width: 170,
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 80,
          align: 'center',
          filters:[
            { text: '未推送', value: 'unlink'},
            { text: '推送中', value: 'linking'},
            { text: '已推送', value: 'linked'},
          ],
        },
        {
          title: '已链接',
          dataIndex: 'linkDir',
          key: 'linkDir',
          width: 100,
          align: 'center',
          filters:[
            { text: '是', value: 'yes'},
            { text: '否', value: 'no'},
          ],
        },
        // {
        //   title: '描述',
        //   dataIndex: 'description',
        //   key: 'description',
        // },
        {
          title: 'Action',
          key: 'action',
          fixed: 'right',
          width: 200,
        },
      ],
      dataLoading:false, data:[],
      form: {},
      pulling: false,
      removeShow: false, removeLoading: false,
      removeForm: {
        id: '',
        remove: true,
        del: false,
        delFile: false,
      },
      linkShow: false, linkLoading: false,
      linkForm: {
        id: '',
        clientid: '',
        hashString: '',
        checkInClient: true,
      },
      linkRules: {
        clientid: [
          { required: true, message: '请选择下载器', trigger: 'change', type: 'number' },
        ],
        hashString: [
          { required: true, message: '请填写hash值', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    BaseApi.siteOptions().then(response => {
        this.siteOptions = response.data.data
    })
    BaseApi.categoryOptions().then(response => {
        this.categoryOptions = response.data.data
    })
    BaseApi.clientOptions().then(response => {
        this.clientOptions = response.data.data
    })
    BaseApi.libraryOptions().then(response => {
        this.libraryOptions = response.data.data
    })
  },
  mounted() {
    this.loadData()
  },
  methods: {
    doSearch() {
      this.searchForm.current = 1
      this.reloadData()
    },
    tableChange(pagination, filters, sorter) {
      this.searchForm.current = pagination.current
      this.searchForm.pageSize = pagination.pageSize
      this.searchForm.sortField = sorter.field
      this.searchForm.sortOrder = sorter.order
      this.searchForm = {...this.searchForm, ...filters}
      this.reloadData()
    },
    reloadData(){
      this.data = []
      this.loadData()
    },
    loadData() {
      this.dataLoading = true
      if (!this.searchForm.sortField) this.searchForm.sortField = 'addtime'
      if (!this.searchForm.sortOrder) this.searchForm.sortOrder = 'descend'
      BaseApi.list(this.module, this.searchForm).then(response=>{
        if (response.data.code === 1) {
          this.data = response.data.data.rows
          this.pagination.current = response.data.data.current
          this.pagination.pageSize = response.data.data.pageSize
          this.pagination.total = response.data.data.total
        } else {
          this.$message.error(`数据加载失败：${response.data.message}`)
        }
      }).catch((error)=>{
        this.$message.error(`数据加载失败：${error.message}`)
      }).then(()=>{
        this.dataLoading = false
      })
    },
    toAdd() {
      if (this.form.id) {
        this.form = {
          clientid: []
        }
      }
      this.$refs.addModal.open(this.form)
    },
    toEdit(record) {
      this.form.id = record.id
      this.form.name = record.name
      this.form.torrentFile = record.torrentFile
      this.form.address = record.address
      this.form.siteid = record.siteid
      this.form.categoryid = record.categoryid
      this.form.clientid = record.clientid
      this.form.description = record.description
      this.form.autoLink = record.autoLink == 1
      this.form.libraryid = record.libraryid
      this.form.toLink = record.toLink
      this.$refs.addModal.open(this.form)
    },
    // doDelete(id) {
    //   BaseApi.del(this.module, id).then(response=>{
    //     if (response.data.code === 1) {
    //       this.$message.success('删除成功')
    //       this.reloadData()
    //     } else {
    //       this.$message.error(`删除失败：${response.data.message}`)
    //     }
    //   }).catch((error)=>{
    //     this.$message.error(`删除失败：${error.message}`)
    //   }).then(()=>{
    //   })
    // },
    doUpdate(data) {
      BaseApi.update(this.module, data).then(response => {
          if (response.data.code === 1) {
            this.$message.success('修改成功', 1)
          } else {
            this.$message.error(`修改失败：${response.data.message}`)
          }
        }).catch((error)=>{
          this.$message.error(`修改失败：${error.message}`)
        })
    },
    toView(record) {
      let siteName,categoryName,clientName,libraryName
      if (record.siteid) {
        const finded = this.siteOptions.find(op=>op.id===record.siteid)
        siteName = finded?finded.name:'（未设置）'
      }
      if (record.categoryid) {
        const finded = this.categoryOptions.find(op=>op.id===record.categoryid)
        categoryName = finded?finded.name:'（未设置）'
      }
      if (record.clientid) {
        const finded = this.clientOptions.find(op=>op.id===record.clientid)
        clientName = finded?finded.name:'（未设置）'
      }
      if (record.libraryid) {
        const finded = this.libraryOptions.find(op=>op.id===record.libraryid)
        libraryName = finded?finded.name:'（未设置）'
      }
      this.$refs.detailModal.open({...record, siteName, categoryName, clientName, libraryName})
    },
    doPull(e) {
      if (!e.key) return
      this.pulling = true
      const hide = this.$message.loading('同步中，请耐心等待', 0)
      TorrentApi.downloadFromClient(e.key).then(response=>{
        if (response.data.code === 1) {
            this.$message.success('同步成功')
            this.reloadData()
          } else {
            this.$message.error(`同步失败：${response.data.message}`)
          }
      }).catch((error)=>{
        this.$message.error(`同步失败：${error.message}`)
      }).then(()=>{
        this.pulling = false
        hide()
      }) 
    },
    statusEvent(record) {
      if (record.status === 'unlink') {
        this.$message.success("推送下载")
      } else if (record.status === 'linked') {
        this.$message.success("解除推送")
      } else if (record.status === 'linking') {
        this.$message.success("正在推送中...")
      }
    },
    toRemove(record) {
      this.removeForm.id = record.id
      this.removeForm.remove = true
      this.removeForm.del = false
      this.removeForm.delFile = false

      this.removeShow = true
    },
    doRemove() {
      this.removeLoading = true
      TorrentApi.removeTorrent(this.removeForm).then(response=>{
        if (response.data.code === 1) {
          this.reloadData()
          this.removeShow = false
          this.$message.success('删除成功')
        } else {
          this.$message.error(`删除失败：${response.data.message}`)
        }
      }).catch((error)=>{
        this.$message.error(`删除失败：${error.message}`)
      }).then(()=>{
        this.removeLoading = false
      })
    },
    toLink(record) {
      this.linkForm.id = record.id
      this.linkForm.clientid= record.clientid
      this.linkForm.hashString = record.hashString

      this.linkShow = true
    },
    doLink() {
      this.$refs.linkForm
      .validate()
      .then(async () => {
        this.linkLoading = true
        TorrentApi.linkToClient(this.linkForm).then(response=>{
          if (response.data.code === 1) {
            this.reloadData()
            this.linkShow = false
            this.$message.success('关联成功')
          } else {
            this.$message.error(`关联失败：${response.data.message}`)
          }
        }).catch((error)=>{
          this.$message.error(`关联失败：${error.message}`)
        }).then(()=>{
          this.linkLoading = false
        })
      })
      .catch(error => {
        console.log('error', error);
      })
    },
    toAutoLink(dryRun) {
      TorrentApi.autoLink(dryRun).then(response=>{
        if (response.data.code === 1) {
          if (dryRun) {
            console.log(response.data.data);
          } else {
            this.$message.success('自动链接开始')
          }
        } else {
          this.$message.error(`自动链接失败：${response.data.message}`)
        }
      }).catch((error)=>{
        this.$message.error(`自动链接失败：${error.message}`)
      })
    }
  }
}
</script>
<style scoped>
.search-box ::v-deep(.ant-form-item){
  margin-bottom: 0px;
}
.icon-font {
  font-size: 24px;
}
.info-card-label {
  text-align: right;
}
.info-card-content {
  text-align: left;
}
</style>